<template>
  <div class="customer-service" :class="{ 'dark': isDark }">
    <div class="chat-container">
      <div class="sidebar">
        <div class="history-header">
          <h2>咨询记录</h2>
          <button class="new-chat"
                  @click="startNewChat">
            <PlusIcon class="icon" />
            新咨询
          </button>
        </div>
        <div class="history-list">
          <div
              v-for="chat in chatHistory"
              :key="chat.id"
              class="history-item"
              :class="{ 'active': currentChatId === chat.id }"
              @click="loadChat(chat.id)"
          >
            <ChatBubbleLeftRightIcon class="icon" />
            <span class="title">{{ chat.title || '新咨询' }}</span>
          </div>
        </div>
      </div>

      <div class="chat-main">
        <div class="service-header">
          <div class="service-info">
            <ComputerDesktopIcon class="avatar" />
            <div class="info">
              <h3>小飞</h3>
              <p>故障诊断智能助手</p>
            </div>
          </div>
        </div>

        <div class="messages" ref="messagesRef">
          <ChatMessage
              v-for="(message, index) in currentMessages"
              :key="index"
              :message="message"
              :is-stream="isStreaming && index === currentMessages.length - 1"
          />
        </div>

        <div class="input-area">
          <!-- 语音 -->
          <el-button
              type="primary"
              plain
              icon="Microphone"
              @click="handleVoiceClick"
              :disabled="voiceIsListening || isSpeaking"
              :loading="voiceIsListening"
          >
            <!-- 根据识别状态显示不同文本 -->
            <template #default>
              {{ voiceIsListening ? '正在识别...' : '语音输入' }}
            </template>
          </el-button>

          <textarea
              v-model="userInput"
              @keydown.enter.prevent="sendMessage()"
              placeholder="请输入您的问题..."
              rows="1"
              ref="inputRef"
          ></textarea>
          <button
              class="send-button"
              @click="sendMessage()"
              :disabled="isStreaming || !userInput.trim()"
          >
            <PaperAirplaneIcon class="icon" />
          </button>
        </div>
      </div>
    </div>

    <!-- 预约成功弹窗 -->
    <div v-if="showBookingModal" class="booking-modal">
      <div class="modal-content">
        <h3>预约成功！</h3>
        <div class="booking-info" v-html="bookingInfo"></div>
        <button @click="showBookingModal = false">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useDark } from '@vueuse/core'
import { marked } from 'marked'
import {
  ChatBubbleLeftRightIcon,
  PaperAirplaneIcon,
  PlusIcon,
  ComputerDesktopIcon
} from '@heroicons/vue/24/outline'
import ChatMessage from '../components/ChatMessage.vue'
import { chatAPI } from '../services/api'
import { useVoice } from '@/hooks/useVoice';

// 引入外部CSS文件
import '@/assets/CustomerService.css'

const isDark = useDark()
const messagesRef = ref(null)
const inputRef = ref(null)
const userInput = ref('')
const isStreaming = ref(false)
const currentChatId = ref(null)
const currentMessages = ref([])
const chatHistory = ref([])
const showBookingModal = ref(false)
const bookingInfo = ref('')
const websocket = ref(null)

// 使用语音Hook：传入识别结果的处理函数
const {
  voiceIsListening,  // 从Hook获取状态
  isSpeaking,
  startVoiceRecognition,
  stopVoiceRecognition,
  speakResponse,
  stopSpeaking,
  ifSpeakGetInput
} = useVoice((transcript) => {
  // 语音识别结果的处理逻辑（追加到输入框）
  userInput.value += transcript;
  // 若需要自动调整输入框高度，调用现有方法
  adjustTextareaHeight();
});

// 初始化WebSocket连接
const initWebSocket = () => {
  // 创建WebSocket连接 (假设后端WebSocket服务地址为ws://localhost:8000)
  const wsUrl = 'ws://localhost:3000'
  websocket.value = new WebSocket(wsUrl)
  
  // 监听连接打开
  websocket.value.onopen = () => {
    console.log('WebSocket连接已建立')
  }
  
  // 监听消息接收
  websocket.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      
      // 处理用户身份信息
      if (data.type === 'user_info') {
        handleUserInfo(data)
      }
      
      // 可以在这里处理其他类型的消息
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
    }
  }
  
  // 监听连接关闭
  websocket.value.onclose = () => {
    console.log('WebSocket连接已关闭')
  }
  
  // 监听连接错误
  websocket.value.onerror = (error) => {
    console.error('WebSocket连接错误:', error)
  }
}

// 处理用户身份信息并进行语音播报
const handleUserInfo = (userInfo) => {
  const { user_id, user_role } = userInfo
  
  // 构造要播报的信息
  let announcement = ''
  if (user_id === 'guest') {
    announcement = '欢迎访客用户'
  } else {
    announcement = `欢迎${user_role}${user_id}`
  }
  
  // 使用现有的语音功能进行播报
  speakResponse(announcement)
}

// 配置 marked
marked.setOptions({
  breaks: true,  // 支持换行
  gfm: true,     // 支持 GitHub Flavored Markdown
  sanitize: false // 允许 HTML
})

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  const textarea = inputRef.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = textarea.scrollHeight + 'px'
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 语音按钮点击事件（支持切换"开始/停止"）
const handleVoiceClick = () => {
  if (voiceIsListening.value) {
    // 正在识别时，点击停止
    stopVoiceRecognition();
  } else {
    // 未识别时，点击开始
    startVoiceRecognition();
  }
};

const sendMessage = async (content) => {
  if (isStreaming.value || (!content && !userInput.value.trim())) return;

  const messageContent = content || userInput.value.trim();
  const userMessage = {
    role: 'user',
    content: messageContent,
    timestamp: new Date()
  };
  currentMessages.value.push(userMessage);

  if (!content) {
    userInput.value = '';
    adjustTextareaHeight();
  }
  await scrollToBottom();

  currentMessages.value.push({
    role: 'assistant',
    content: '',
    timestamp: new Date(),
    isMarkdown: true,
    hasChart: false,
    chartData: null
  });
  isStreaming.value = true;

  let hasProcessedTemperature = false;
  let accumulatedText = '';
  let errorDetails = '';
  let buffer = ''; //缓存不完整的JSON片段

  try {
    const reader = await chatAPI.sendServiceMessage(messageContent, currentChatId.value);
    const decoder = new TextDecoder('utf-8');

    while (true) {
      const { value, done } = await reader.read();
      if (done) {
        // 处理最后剩余的缓冲数据
        if (buffer.trim()) {
          try {
            const data = JSON.parse(buffer);
            processData(data); // 复用数据处理逻辑
          } catch (e) {
            console.warn('流结束时剩余未解析数据:', buffer);
          }
        }
        break;
      }

      // 解码当前块并添加到缓冲区
      buffer += decoder.decode(value, { stream: true });

      // 按行分割（NDJSON格式的标准处理方式）
      const lines = buffer.split('\n');
      // 最后一行可能不完整，留到下次处理
      buffer = lines.pop() || '';

      // 处理完整的行
      for (const line of lines) {
        if (!line.trim()) continue; // 跳过空行
        try {
          const data = JSON.parse(line);
          processData(data); // 统一处理数据
        } catch (parseError) {
          errorDetails = `数据解析错误: ${parseError.message}，行内容: ${line}`;
          console.error(errorDetails);
          throw new Error(errorDetails);
        }
      }
    }

    // 🔥 后端数据完整后，调用朗读方法
    if (ifSpeakGetInput.value && buffer.trim()) {
      speakResponse(buffer);
    }

    //console.log("总信息", currentMessages.value);
    //console.log("信息列表", currentMessages.value.at(-1));

  } catch (error) {
    console.error('发送消息失败:', error);
    const userFriendlyMessage = errorDetails
        ? `请求处理失败: ${errorDetails}`
        : '请求处理失败，请重试。';

    const lastIndex = currentMessages.value.length - 1;
    currentMessages.value.splice(lastIndex, 1, {
      ...assistantMessage,
      content: userFriendlyMessage
    });
  } finally {
    isStreaming.value = false;
    await scrollToBottom();
  }

  // 提取数据处理逻辑为函数，避免重复代码
  function processData(data) {
    // 🔥 关键：获取响应式数组中当前的 assistant 消息对象
    const currentAssistantMsg = currentMessages.value.at(-1);

    // 处理图表数据：将chartData赋值给assistant消息的chartData属性
    if (data.type === 'chartData' ) {
      console.log("温度数据", data);
      nextTick(() => {
        currentMessages.value.splice(currentMessages.value.length - 1, 1, {
          ...currentAssistantMsg,
          chartData: data.chartData // 将后端返回的chartData直接传递
        });
      });
    }

    // 🔥 新增：处理花卉问题
    if (data.type === "flower_problem" && data.api_url && data.request_data) {
      handleFlowerProblem(data);
      return;
    }

    // 处理错误类型响应
    if (data.type === 'error' && data.content) {
      errorDetails = `服务器错误: ${data.content}`;
      console.error(errorDetails);
      throw new Error(errorDetails);
    }

    // 文本内容处理（同样修改响应式数组中的对象）
    if (data.type === 'text' && data.content) {
      accumulatedText += data.content;
      nextTick(() => {
        currentMessages.value.splice(currentMessages.value.length - 1, 1, {
          ...currentAssistantMsg,
          content: accumulatedText
        });
      });
      scrollToBottom();
    }
  }
}

// 加载特定对话
const loadChat = async (chatId) => {
  currentChatId.value = chatId
  try {
    const messages = await chatAPI.getChatMessages(chatId, 'service')
    currentMessages.value = messages.map(msg => ({
      ...msg,
      isMarkdown: msg.role === 'assistant'  // 为助手消息添加 Markdown 标记
    }))
  } catch (error) {
    console.error('加载对话消息失败:', error)
    currentMessages.value = []
  }
}

// 加载聊天历史
const loadChatHistory = async () => {
  try {
    const history = await chatAPI.getChatHistory('service')
    chatHistory.value = history || []
    if (history && history.length > 0) {
      await loadChat(history[0].id)
    } else {
      await startNewChat()  // 等待 startNewChat 完成
    }
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    chatHistory.value = []
    await startNewChat()  // 等待 startNewChat 完成
  }
}

// 🔥 新增：处理花卉问题的函数
const handleFlowerProblem = async (flowerData) => {
  try {
    // 显示检测到花卉问题的消息（根据指导文档先显示原始消息）
    const lastIndex = currentMessages.value.length - 1;
    currentMessages.value.splice(lastIndex, 1, {
      ...currentMessages.value[lastIndex],
      content: flowerData.message || "检测到花卉相关问题，将启用花卉助手处理"
    });
    await scrollToBottom();

    // 调用花卉专用API（根据API文档和指导文档）
    const response = await fetch(flowerData.api_url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: flowerData.request_data.message,
        session_id: flowerData.request_data.session_id || "default",
        response_type: flowerData.request_data.response_type || "text"
      })
    });

    if (!response.ok) {
      throw new Error(`花卉API请求失败: ${response.status}`);
    }

    const data = await response.json();

    // 更新消息内容为花卉API返回的结果（根据API文档格式化）
    currentMessages.value.splice(lastIndex, 1, {
      ...currentMessages.value[lastIndex],
      content: formatFlowerApiResponse(data)
    });

    await scrollToBottom();

    // 如果开启了语音，则朗读结果
    if (ifSpeakGetInput.value) {
      speakResponse(formatFlowerApiResponse(data));
    }
  } catch (error) {
    console.error('处理花卉问题失败:', error);
    const lastIndex = currentMessages.value.length - 1;
    currentMessages.value.splice(lastIndex, 1, {
      ...currentMessages.value[lastIndex],
      content: '查询花卉设备数据时发生错误，请稍后重试。'
    });
  }
};

// 🔥 新增：格式化花卉API响应（根据API文档）
const formatFlowerApiResponse = (data) => {
  if (!data || typeof data !== 'object') {
    return JSON.stringify(data, null, 2);
  }

  // 如果是错误信息
  if (data.error) {
    return `查询出错: ${data.error}`;
  }

  // 根据API文档，主要信息在response字段中
  if (data.response) {
    return typeof data.response === 'string' ? data.response : JSON.stringify(data.response, null, 2);
  }

  // 如果有message字段，直接返回
  if (data.message) {
    return data.message;
  }

  // 格式化为键值对显示
  let formatted = "花卉设备数据:\n\n";
  for (const [key, value] of Object.entries(data)) {
    formatted += `${key}: ${typeof value === 'object' ? JSON.stringify(value) : value}\n`;
  }

  return formatted;
};

// 开始新对话
const startNewChat = async () => {  // 添加 async
  const newChatId = Date.now().toString()
  currentChatId.value = newChatId
  currentMessages.value = []

  // 添加新对话到历史列表
  const newChat = {
    id: newChatId,
    title: `咨询 ${newChatId.slice(-6)}`
  }
  chatHistory.value = [newChat, ...chatHistory.value]

  // 发送初始问候语
  //await sendMessage('你好')
}

onMounted(() => {
  //loadChatHistory()
  adjustTextareaHeight()
  // 初始化WebSocket连接
  initWebSocket()
})
</script>